<template>
	<div>
		<el-dialog
			:title="isVip ? '修改会员返水比例' : '修改返点信息'"
			center
			:visible.sync="visible"
			width="1200"
			class="audit-confirm"
			:before-close="handleCancel"
		>
			<div class="commissionsDialog">
				<PointAndRebate
					ref="PointAndRebateRef"
					:isVip="isVip"
					:isEdit="isEdit"
					:isTotalAgent="false"
					:data="pointAndRebate"
					:merchantId="row.merchantId"
					labelWidth="170px"
				/>
			</div>
			<div slot="footer" class="dialog-footer">
				<template v-if="isEdit">
					<el-button @click="handleCancel">
						{{ $t('agent.cancel') }}
					</el-button>
					<el-button
						type="primary"
						:loading="loading"
						@click="handleOK"
					>
						{{ $t('agent.submit') }}
					</el-button>
				</template>
			</div>
		</el-dialog>
		<AgentPointSetAllSub
			:loading="agentPointSetAllSub.loading"
			:visible="agentPointSetAllSub.visible"
			:agentPoint="agentPointSetAllSub.agentPoint"
			:agentData="agentPointSetAllSub.agentData"
			@ok="handleRowSubmitFetch"
			@close="handelAgentPointSetAllSubClose"
		/>
	</div>
</template>
<script>
import PointAndRebate from '@/components/PointAndRebate'
import AgentPointSetAllSub from '@/components/AgentPointSetAllSub'

export default {
	name: 'CommissionsDialog',
	components: {
		PointAndRebate,
		AgentPointSetAllSub
	},
	props: {
		visible: {
			type: Boolean,
			default: false
		},
		isEdit: {
			type: Boolean,
			default: false
		},
		row: {
			type: Object,
			default: () => ({})
		},
		// eslint-disable-next-line vue/require-default-prop, vue/require-prop-types
		refresh: {
			typeof: Function
		},
		teamAgent: {
			type: Object,
			default: () => ({})
		}
	},
	data() {
		return {
			loading: false,
			agentPointSetAllSub: {
				loading: false,
				visible: false,
				agentPoint: {},
				agentData: {}
			},
			pointAndRebate: {
				commissionModel: 1,
				rebateRateList: [],
				rebateRateTemplateName: undefined,
				rebateRateTemplateId: undefined,
				rebateAllotMode: this.row.rebateAllotMode || 2
			}
		}
	},
	computed: {
		isVip() {
			return this.row.userType === 0
		}
	},
	watch: {
		visible: {
			handler(newVal, oldVal) {
				if (newVal) {
					this.queyrRate()
					this.pointAndRebate.rebateAllotMode = this.row.rebateAllotMode
					this.pointAndRebate.rebateRateTemplateId = this.row.rebateRateTemplateId
					this.pointAndRebate.rebateRateTemplateName = this.row.rebateRateTemplateName
				}
			}
		}
	},
	methods: {
		handelAgentPointSetAllSubClose() {
			this.agentPointSetAllSub.visible = false
		},

		// 团队返点保存接口
		async handleRowSubmitFetch(params) {
			const {
				rebateRateList,
				rebateAllotMode,
				rebateRateTemplateId
			} = this.$refs['PointAndRebateRef'].getValues()
			try {
				const row = this.row
				const _rebateRateList = rebateRateList.filter((item) => {
					return item.platformFlag === row.platformFlag
				})
				let res = {}
				// 模板分配
				if (rebateAllotMode === 2) {
					res = await this.$api.updateRebateAllotMode({
						level: 1,
						rebateAllotMode: rebateAllotMode,
						templateId: rebateRateTemplateId,
						sourceTemplateId: this.row.rebateRateTemplateId,
						topProxyId: row.topProxyId,
						userId: row.topProxyId,
						userType: row.userType
					})
				} else {
					res = await this.$api.rebateRateUdate({
						userType: row.userType,
						merchantId: row.merchantId,
						userId: row.topProxyId,
						...params,
						rebateAllotMode: rebateAllotMode,
						rebateRateList: _rebateRateList
					})
				}

				if (res.code === 200) {
					this.$message.success(this.$t('common.save_success'))
					this.$emit('refresh')
					this.handleCancel()
				}
			} catch (err) {
				throw err
			}
		},
		checkMax(field, value) {
			const path = field.split('.') || {}
			const key = path[2]
			if (key && this.teamAgent[key] !== undefined) {
				const max = this.teamAgent[key]
				if (parseFloat(value) > max) {
					return `不能大于${max}`
				}
			}
			return false
		},
		handleCancel() {
			this.$emit('update:visible', false)
			this.$refs['PointAndRebateRef'].resetFields()
			this.agentPointSetAllSub.visible = false
		},
		// async queyrTemplateDetail() {
		// 	try {
		// 		const ret = await this.$api.getRebateRateTemplateDetail({
		// 			userId: this.row.topProxyId,
		// 			userType: 1,
		// 			level: 1
		// 		})

		// 		if (ret.code === 200 && ret.data) {
		// 			this.pointAndRebate.rebateRateTemplateName = ret.data[0].templateName
		// 			this.pointAndRebate.rebateRateTemplateId = ret.data[0].templateId
		// 		}
		// 	} catch (err) {
		// 		throw err
		// 	}
		// },
		async handleOK() {
			try {
				await this.$refs['PointAndRebateRef'].validate()
				const { rebateRateList, rebateAllotMode } = this.$refs[
					'PointAndRebateRef'
				].getValues()
				if (this.isVip) {
					await this.$confirm(
						`确认修改返水比例后，针对待结算返点账单即刻生效。修改前返水比例将生成已失效记录。`,
						'确认提示'
					)
					const ret = await this.$api.rebateRateUdate({
						rebateRateList: rebateRateList.filter((item) => {
							return item.platformFlag === 1
						}),
						userId: this.row.userId,
						merchantId: this.row.merchantId,
						userType: this.row.userType,
						status: 1
					})
					if (ret.code === 200) {
						this.handleCancel()
						this.$emit('refresh')
						this.$message.success(this.$t('common.save_success'))
					}
				} else {
					// 返点编辑保存
					this.$emit('update:visible', false)
					const agentPoint = rebateRateList.filter((item) => {
						return item.platformFlag === 0
					})[0]

					// 自由模式提交
					if (rebateAllotMode === 1) {
						let isAllNull = true
						Object.keys(agentPoint).forEach((k) => {
							if (k !== 'remark' && agentPoint[k] > 0) {
								isAllNull = false
							}
						})
						if (isAllNull) {
							this.$message.error(
								'全部场馆项目不能全为0，至少1个场馆值>0'
							)
							return
						}
						this.agentPointSetAllSub.visible = true
						this.agentPointSetAllSub.agentPoint = agentPoint
						this.agentPointSetAllSub.agentData = {
							merchantId: this.row.merchantId,
							id: this.row.topProxyId,
							topProxyName: this.row.topProxyName
						}
					}
					// 模板模式提交
					if (rebateAllotMode === 2) {
						this.handleRowSubmitFetch()
					}
				}
			} catch (err) {
				console.error(err)
				throw err
			}
		},
		async queyrRate() {
			try {
				this.loading = true
				const params = {
					merchantId: this.row.merchantId,
					userName: this.row.userName,
					// status: this.row.status,
					userType: this.row.userType
				}
				if (this.row.status === 2) {
					params.version = this.row.version
				}
				const res = await this.$api.rebateRateQuery(params)
				this.loading = false
				if (res.code === 200 && res.data.length > 0) {
					// 代理
					const platformFlag_0 = res.data.find((item) => {
						return (
							item.userType === this.row.userType &&
							item.platformFlag === 0 &&
							item.status === this.row.status &&
							item.zhanchengFlag === 0
						)
					}) || { platformFlag: 0 }
					// 平台
					const platformFlag_1 = res.data.find((item) => {
						return (
							item.userType === 0 &&
							item.platformFlag === 1 &&
							item.status === 1 &&
							item.zhanchengFlag === 0
						)
					}) || { platformFlag: 1 }

					this.pointAndRebate.rebateRateList = [
						platformFlag_0,
						platformFlag_1
					]
				}
			} catch (err) {
				throw err
			} finally {
				this.loading = false
			}
		}
	}
}
</script>

<style scoped>
::v-deep .commissionsDialog .commissionModel {
	display: none;
}
/* ::v-deep .commissionsDialog .pointTable {
        display: none;
    } */
</style>
